#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import conf
import paper
import xnuser
import antispam

class MainPage(webapp.RequestHandler):
    def get(self):
        rssAuthorId = self.request.get('id')
        rssAuthorName = ''
        if rssAuthorId:
            try:
                rssAuthorId = int(rssAuthorId)
            except ValueError:
                rssAuthorId = 0
            if rssAuthorId:
                xnUserModel = xnuser.getXnUserById(rssAuthorId)
                if xnUserModel:
                    rssAuthorName = xnUserModel.name

        paperList = []
        #Send latest 15 papers as RSS feed
        offset = 0
        limit = 15
        if rssAuthorId:
            paperList = paper.listPapersByAuthor(rssAuthorId, offset, limit)
        else:
            paperList = paper.listAllPapers(offset, limit)
        for paperModel in paperList:
            filteredContent = antispam.filter(paperModel.content, htmlEncodingMode=False, stripTagMode=True)
            #get the first 1000 characters at most
            if filteredContent:
                lenContent = len(filteredContent)
                if lenContent >= 1000:
                    maxIndex = 1000
                else:
                    maxIndex = lenContent
                paperModel.filteredContent = filteredContent[0:maxIndex] + '......'
            else:
                paperModel.filteredContent =  'None'

        templateValues = {
            'siteUrl': conf.siteUrl,
            'rssAuthorId': rssAuthorId,
            'rssAuthorName': rssAuthorName,
            'paperList': paperList
        }
        self.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        path = os.path.join(os.path.dirname(__file__), 'pages/rss.xml')
        self.response.out.write(template.render(path, templateValues))


application = webapp.WSGIApplication(
                                     [('/rss\.xml', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

